package com.stillalive.springcaptcha;

import cn.hutool.captcha.CaptchaUtil;
import cn.hutool.captcha.ShearCaptcha;
import com.stillalive.springcaptcha.model.CaptchaProperties;
import jakarta.servlet.http.HttpServletResponse;
import jakarta.servlet.http.HttpSession;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.io.IOException;
import java.util.Date;

@RequestMapping("/captcha")
@RestController
public class CaptchaController {

    @Autowired
    private CaptchaProperties captchaProperties;
    // 这个时间不能太短（单位是ms）
    private final static Long VALID_TIME = 2*60*1000L;
    private Date date;

    @RequestMapping("/getCaptcha")
    // 返回生成的验证码图片（发送到浏览器）
    public void getCaptcha(HttpServletResponse response, HttpSession session) {
        // 设置返回结果类型
        response.setContentType("image/jpeg");
        // 生成验证码
        try {
            ShearCaptcha captcha = CaptchaUtil.createShearCaptcha(captchaProperties.getLength(), captchaProperties.getHeigh(), 4, 4);
            String code = captcha.getCode();
            session.setAttribute(captchaProperties.getSession().getKey(), code);
            session.setAttribute(captchaProperties.getSession().getDate(), new Date());
            captcha.write(response.getOutputStream());
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }

    @RequestMapping("/checkCaptcha")
    public boolean checkCaptcha(String captcha, HttpSession session){
        if(!StringUtils.hasLength(captcha)){
            return false;
        }

        // 验证是否过期
        String code = (String)session.getAttribute(captchaProperties.getSession().getKey());
        Date date = (Date)session.getAttribute(captchaProperties.getSession().getDate());
        if(captcha.equals(code) && date != null && (System.currentTimeMillis() - (Long)date.getTime() < VALID_TIME)){
            return true;
        }
        return false;
    }
}
